import './CV'
// import './jquery.animate'

(function (root) {
root.login = {
  init: function () {
    console.log("pass params this");
  }
}

var LoginModule =  CV.ControllerView.extend({
  el:".login-wrapper",
  events:{
    "click .login-btn": "submit",
    "keyup .username": "verifyUsername",
    "keyup .password": "verifyPassword",
  },
  initKey: {
    test:"112",
    err_username: "请输入账号",
    err_password: "请输入密码"
  },
  initialize: function () {
  },
  verifyUsername: function (e) {
    this.observer["username"] = e.target.value;
    if (this.observer["username"]) {
      $(".err-message.username").removeClass("err-show");
    } else {
      this.observer["err_username"] =  "请输入账号";
      $(".err-message.username").addClass("err-show");
    }
  },
  verifyPassword: function (e) {
    this.observer["password"] = e.target.value;
    if (this.observer["password"]) {
      $(".err-message.password").removeClass("err-show");
      e.keyCode == 13 && this.submit();
    } else {
      this.observer["err_password"] =  "请输入密码";
      $(".err-message.password").addClass("err-show");
    }
  },
  submit: function () {
    var self = this;
    var username = document.querySelector(".username").value;
    var password = document.querySelector(".password").value;
    if (!username) {
      $(".err-message.username").addClass("err-show");
      return ;
    }
    if (!password) {
      $(".err-message.password").addClass("err-show");
      return ;
    }

    if (/admin/.test(location.pathname)) {
      CV.httpService("POST", "/admin/login", {username:username, password: password}, function (data) {
        console.log(data);
        if (data.code == 0) {
          window.location.href = '/admin/index';
          localStorage.setItem("user_info", JSON.stringify(data.data));
        } else if (data.message.match("用户名")) {
          $(".err-message.username").addClass("err-show");
          self.observer["err_username"] = data.message;
        } else if (data.message.match("密码")) {
          $(".err-message.password").addClass("err-show");
          self.observer["err_password"] = data.message;
        }
      }, function (data) {
         self.observer["err_password"] = "网络异常";
      })
    } else {
      CV.httpService("POST", "/login", {username:username, password: password}, function (data) {
        console.log(data);
        if (data.code == 0) {
          window.location.href = '/';
          localStorage.setItem("user_info", JSON.stringify(data.data));
        } else if (data.message.match("用户名")) {
          $(".err-message.username").addClass("err-show");
          self.observer["err_username"] = data.message;
        } else if (data.message.match("密码")) {
          $(".err-message.password").addClass("err-show");
          self.observer["err_password"] = data.message;
        }
      }, function (data) {
         self.observer["err_password"] = "网络异常";
      })
    }
  }
})

var loginModule = new LoginModule();

}(window))
